﻿using System;

public delegate void TickHandler();
/// <summary>
/// Tick.时间管理器cyb
/// </summary>
public class Tick
{
	protected int mDelay;
	protected TickHandler mHandler;

	private int m_Timer = 0;
	private int m_StopTime = 0;	//停止时间
	private int m_AccumulativeTime = 0;	//累计时间
	private bool m_StopFlag = true;
	private bool m_EndFlag = false;


	public Tick (int delay ,int stopTime )
	{
		this.mDelay = delay;
		this.m_StopTime = stopTime;
		TickManager.Instance.addTick (this);
	}

	public void setCallBack(TickHandler callBack) 
	{
		mHandler = callBack;
	}


	public void onTick(int timeElapsed)
	{
		if(isEnd()) return;
		if(isStop()) return;
		if(m_StopTime > 0)
		{
			//TODO cyb:这里面有个错误，不太精确，会导致应该执行的update()没有执行
			m_AccumulativeTime += timeElapsed;
			if(m_AccumulativeTime > m_StopTime)
			{
				stop();
				return;	
			}
		}
		if(mDelay > 0) 
		{
			m_Timer += timeElapsed;
			while(m_Timer >= mDelay)
			{
				update();
				m_Timer -= mDelay;
				if(isEnd()) break;
				if(isStop()) break;
			}
		}

	}


	protected void update() 
	{
		if(null != mHandler) 
			mHandler();
	}
	public void start()
	{
		m_StopFlag = false;
	}

	public void reStart()
	{
		m_StopFlag = false;
		m_Timer = 0;
		m_AccumulativeTime = 0;
		//先执行一次
		//			update();
	}

	public void stop()
	{
		m_StopFlag = true;
		//			trace("stop");
	}

	public bool isStop()
	{
		return m_StopFlag;
	}

	public bool isEnd()
	{
		return m_EndFlag;
	}

	public void onDispose()
	{
		stop();
		mHandler = null;
	}



}


